/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.listener;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.messages.request.BeginRequestMessage;
import cn.easyplatform.messages.vos.AbstractPageVo;
import cn.easyplatform.messages.vos.MenuNodeVo;
import cn.easyplatform.messages.vos.TaskVo;
import cn.easyplatform.spi.service.TaskService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.dialog.ActionEvent;
import cn.easyplatform.web.dialog.MessageBox;
import cn.easyplatform.web.layout.IMainTaskBuilder;
import cn.easyplatform.web.layout.LayoutManagerFactory;
import cn.easyplatform.web.log.LogManager;
import cn.easyplatform.web.service.ServiceLocator;
import cn.easyplatform.web.task.BackendException;
import cn.easyplatform.web.task.MainTaskSupport;
import cn.easyplatform.web.utils.TaskInfo;
import cn.easyplatform.web.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RunTaskListener implements EventListener<Event> {

    private final static Logger log = LoggerFactory.getLogger(RunTaskListener.class);

    private MenuNodeVo menu;

    private Component container;

    public RunTaskListener(MenuNodeVo menu, Component container) {
        this.menu = menu;
        this.container = container;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.zkoss.web.ui.event.EventListener#onEvent(org.zkoss.web.ui.event.Event)
     */
    @Override
    public void onEvent(Event event) throws Exception {
        try {
            LogManager.beginRequest();
            TaskInfo taskInfo = new TaskInfo(menu.getId());
            int c = WebUtils.checkTask(taskInfo, container);
            if (c == 1 || c == 0) {
                if (c == 1)
                    MessageBox.showMessage(Labels
                            .getLabel("message.dialog.title.error"), Labels
                            .getLabel("main.task.has.run",
                                    new String[]{menu.getName()}));
                return;
            }
            TaskService mtc = ServiceLocator
                    .lookup(TaskService.class);
            TaskVo tv = new TaskVo(menu.getId());
            tv.setRoleId(menu.getRoleId());
            tv.setAgentId(menu.getAgent());
            BeginRequestMessage req = new BeginRequestMessage(tv);
            if (event instanceof ActionEvent) {
                ActionEvent evt = (ActionEvent) event;
                req.setId(evt.getId());
                req.setActionFlag(evt.getActionFlag());
            }
            IResponseMessage<?> resp = mtc.begin(req);
            if (resp.isSuccess()) {
                if (resp.getBody() != null
                        && resp.getBody() instanceof AbstractPageVo) {
                    AbstractPageVo pv = (AbstractPageVo) resp.getBody();
                    taskInfo.setId(pv.getId());
                    taskInfo.setTitle(pv.getTitile());
                    taskInfo.setImage(pv.getImage());
                    WebUtils.registryTask(taskInfo);
                    MainTaskSupport builder = null;
                    try {
                        builder = (MainTaskSupport) LayoutManagerFactory
                                .createLayoutManager()
                                .getMainTaskBuilder(container,
                                        menu.getId(), pv);
                        ((IMainTaskBuilder) builder).build();
                    } catch (EasyPlatformWithLabelKeyException ex) {
                        builder.close(false);
                        MessageBox.showMessage(ex);
                    } catch (BackendException ex) {
                        builder.close(false);
                        MessageBox.showMessage(ex.getMsg().getCode(), (String) ex
                                .getMsg().getBody());
                    } catch (Exception ex) {
                        if (log.isErrorEnabled())
                            log.error("doTask", ex);
                        builder.close(false);
                        MessageBox.showMessage(
                                Labels.getLabel("message.dialog.title.error"),
                                ex.getMessage());
                    }
                }
            } else
                MessageBox.createDialog(resp, this).show();
        } finally {
            LogManager.endRequest();
        }
    }
}
